import logging as log
import logging.handlers as log_handlers
import os
from enum import Enum

class Handler_type(Enum):
    CONSOLE_HANDLER = 1,
    FILE_HANDLER = 2,

class Custom_Log:
    def __init__(self, enable_console=True, enable_file=True):
        """
        初始化自定义日志系统
        :param enable_console: 是否启用控制台日志 (默认True)
        :param enable_file: 是否启用文件日志 (默认True)
        """
        # 确保日志目录存在
        os.makedirs("log",  exist_ok=True)

        # log.basicConfig(filename="my_log.log",
        #                 filemode="w",
        #                 level=log.DEBUG,
        #                 format="%(asctime)s %(filename)s-%(funcName)s-%(lineno)d %(name)s(%(levelname)s) : %(message)s",
        #                 # datefmt="%Y-%m-%d-%H:%M:%S",
        #                 )

        self.starkLevel = 2

        self.__defaultLevel = log.DEBUG
        self.__logger = log.getLogger("CUSTOM LOG")
        self.__logger.setLevel(self.__defaultLevel)
        self.__format = log.Formatter("%(asctime)s "
                                      "%(filename)s - %(funcName)s - %(lineno)d "
                                      "%(name)s(%(levelname)s) : %(message)s "
                                      )

        # 初始化处理器 (但不立即添加)
        self.__console_handler = None
        self.__file_handler = None

        # 清理旧处理器避免重复
        self.__logger.handlers.clear()

        self.__enable_handler(Handler_type.CONSOLE_HANDLER,enable_console)
        self.__enable_handler(Handler_type.FILE_HANDLER, enable_file)

        # 添加重复日志过滤器
        self.__logger.addFilter(DuplicateFilter())
        self.__logger.propagate  = False



    def SetLevel(self,level):
        self.__logger.setLevel(level)

    def SetConsoleHandler(self):
        if not self.__console_handler:
            self.__console_handler = log.StreamHandler()
            self.__console_handler.setFormatter(self.__format)
            self.__logger.addHandler(self.__console_handler)
    def SetFileHandler(self):
        if not self.__file_handler:
            # self.__file_handler = log.FileHandler(
            #   "log//LogRecord.log",
            #   encoding="utf-8",
            #   mode='w'
            # )
            # self.__file_handler.setFormatter(self.__format)

            # 使用RotatingFileHandler防止日志过大
            self.__file_handler = log.handlers.RotatingFileHandler(
                "log/LogRecord.log",
                encoding="utf-8",
                maxBytes=10*1024*1024,  # 10MB
                backupCount=5,
                delay=True  # 延迟打开文件提升性能
            )
            self.__file_handler.setFormatter(self.__format)
            self.__logger.addHandler(self.__file_handler)

    def __enable_handler(self,handler_type,enable):
        if(handler_type == Handler_type.CONSOLE_HANDLER):
            self.Set_console_handler_enable(enable)
        elif(handler_type == Handler_type.FILE_HANDLER):
            self.Set_file_handler_enable(enable)
        else:
            self.__logger.warning(f'handler_type{type} is not matching'.format(type = handler_type))

    def Set_console_handler_enable(self,enable):
        if (enable):
            self.__enable_console_handler()
            # self.__logger.info('console log enable')
        else:
            self.__disable_console_handler()
            # self.__logger.info('console log diable')
    def Set_file_handler_enable(self, enable):
        if (enable):
            self.__enable_file_handler()
            # self.__logger.info('file log enable')
        else:
            self.__disable_file_handler()
            # self.__logger.info('file log diable')

    # # 控制台log以及日志文件log的开关控制函数
    def __enable_console_handler(self):
        """启用控制台日志输出"""
        if not self.__console_handler:
            self.__console_handler = log.StreamHandler()
            self.__console_handler.setFormatter(self.__format)
            self.__logger.addHandler(self.__console_handler)
            self.__console_enable = True

    def __disable_console_handler(self):
        """禁用并清理控制台日志输出"""
        if self.__console_handler:
            self.__logger.removeHandler(self.__console_handler)
            self.__console_handler.close()
            self.__console_handler = None
            self.__console_enable = False

    def __enable_file_handler(self):
        """启用文件日志输出（带日志轮转）"""
        if not self.__file_handler:
            try:
                # self.__file_handler = log.FileHandler(
                #   "log//LogRecord.log",
                #   encoding="utf-8",
                #   mode='w'
                # )
                # self.__file_handler.setFormatter(self.__format)

                # 使用RotatingFileHandler防止日志过大
                self.__file_handler = log_handlers.RotatingFileHandler(
                    "log/LogRecord.log",
                    mode='w',
                    encoding="utf-8",
                    maxBytes=10 * 1024 * 1024,  # 10MB
                    backupCount=5,
                    delay=True # 延迟打开文件提升性能
                )
                self.__file_handler.setFormatter(self.__format)
                self.__logger.addHandler(self.__file_handler)
                self.__file_enable = True
            except OSError as e:
                self.__logger.info(f" 文件处理器初始化失败: {str(e)}")

    def __disable_file_handler(self):
        """禁用并清理文件日志输出"""
        if self.__file_handler:
            self.__logger.removeHandler(self.__file_handler)
            self.__file_handler.close()  # 确保文件资源释放
            self.__file_handler = None
            self.__file_enable = False

    def shutdown(self):
        """完全关闭日志系统并释放资源"""
        self.__disable_console_handler()
        self.__disable_file_handler()
        log.shutdown()   # 调用全局日志关闭

    def GetHandlerenable(self):
        return {Handler_type.CONSOLE_HANDLER:self.__console_enable, Handler_type.FILE_HANDLER:self.__file_enable}


    # 优化后的日志方法（添加stacklevel=2）
    def Log_debug(self, msg, *args, **kwargs):
        self.__logger.debug(msg, *args, stacklevel=self.starkLevel, **kwargs)

    def Log_info(self, msg, *args, **kwargs):
        self.__logger.info(msg, *args, stacklevel=self.starkLevel, **kwargs)

    def Log_warning(self, msg, *args, **kwargs):
        self.__logger.warning(msg, *args, stacklevel=self.starkLevel, **kwargs)

    def Log_error(self, msg, *args, **kwargs):
        self.__logger.error(msg, *args, stacklevel=self.starkLevel, **kwargs)

    def Log_critical(self, msg, *args, **kwargs):
        self.__logger.critical(msg, *args, stacklevel=self.starkLevel, **kwargs)


# 新增：重复日志过滤器
class DuplicateFilter(log.Filter):
    def __init__(self, name=""):
        super().__init__(name)
        self.last_log = None

    def filter(self, record):
        current_log = (record.module, record.levelno, record.msg)
        if current_log == self.last_log:
            return False
        self.last_log = current_log
        return True


cuslog = Custom_Log()  # 单例模式创建

def Log_Init():

    cuslog.Set_file_handler_enable(False) # 关闭文件日志
    # Cuslog.Set_console_handler_enable(False) # 关闭控制台日志
    for i in range(6):
        cuslog.Log_info('{head},你好'.format(head=i))

if __name__ == "__main__":
    Log_Init()